package com.zxc.behavior.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dto.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.zxc.behavior.service.ApReadBehaviorService;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.heima.common.constants.BehaviorConstants.READ_BEHAVIOR;
import static com.heima.common.constants.HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Resource
    private CacheService cacheService;

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public ResponseResult readCount(ReadBehaviorDto dto) {
        if (dto.getArticleId() == null || dto.getCount() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Object o = cacheService.hGet(READ_BEHAVIOR, dto.getArticleId().toString());
        if (o != null) {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject((String) o, ReadBehaviorDto.class);
            dto.setCount(dto.getCount() + readBehaviorDto.getCount());
        }
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        updateArticleMess.setAdd(1);
        kafkaTemplate.send(HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));

        cacheService.hPut(READ_BEHAVIOR, dto.getArticleId().toString(), JSON.toJSONString(dto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
